package com.ruihang.generalibrary.ui.widget;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build;
import android.support.annotation.AttrRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StyleRes;
import android.util.AttributeSet;
import android.widget.FrameLayout;

import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.R;

/**
 * Created by Administrator on 2017/6/21.
 */

public class CustomExFrameLayout extends FrameLayout {

    private float ratioW;
    private float ratioH;

    public CustomExFrameLayout(@NonNull Context context) {
        super(context);
    }

    public CustomExFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context,attrs,0);
    }

    public CustomExFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context,attrs,defStyleAttr);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public CustomExFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context,attrs,defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthSize = getMeasuredWidth();
        int heightSize = getMeasuredHeight();
//        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
//        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
//        // 计算出所有的childView的宽和高
//        measureChildren(widthMeasureSpec, heightMeasureSpec);
        if (widthSize>0 && isExEnabled()){
            float a= Math.abs(ratioW / ratioH - widthSize*1f / heightSize);
            JLog.e("vvv ws="+widthSize+"  hs="+heightSize+"   a="+a);
            if (a > 0.003) {
                heightSize = (int) (widthSize * ratioH / ratioW);
                setMeasuredDimension(widthSize, heightSize);
                JLog.e("vvv after rest hs="+heightSize);
            }
        }
//        setMeasuredDimension(widthSize, heightSize);

    }

    private void init(@NonNull Context context, @Nullable AttributeSet attrs, int defStyle){
        TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomEXViewAttr, defStyle, 0);
        ratioW=a.getFloat(R.styleable.CustomEXViewAttr_ratioWidth,0);
        ratioH=a.getFloat(R.styleable.CustomEXViewAttr_ratioHeight,0);
    }

    private boolean isExEnabled(){
        return ratioW>0 && ratioH>0;
    }
}
